package com.zygh.lz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.controller.FileUpload;
import com.zygh.lz.dao.*;
import com.zygh.lz.dao.app.AppMenuMapper;
import com.zygh.lz.dao.role.SysUserRoleMapper;
import com.zygh.lz.entity.*;
import com.zygh.lz.entity.app.AppMenu;
import com.zygh.lz.entity.remould.Matching;
import com.zygh.lz.entity.role.SysUserRole;
import com.zygh.lz.entity.signfile.SignBoard;
import com.zygh.lz.service.StaffService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.SysLogAspect;
import com.zygh.lz.util.DataTime;
import com.zygh.lz.util.DistanceUtil;
import com.zygh.lz.util.JwtUtils;
import com.zygh.lz.util.Md5;
import com.zygh.lz.vo.PageUtils;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import com.zygh.lz.vo.RoleUserVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements StaffService {
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private SubsystemMapper subsystemMapper;
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    private GpsMapper gpsMapper;
    @Resource
    private XareaMapper xareaMapper;
    @Resource
    private PatrolrecordMapper patrolrecordMapper;
    @Resource
    private TokenService tokenService;
    @Resource
    private SignMapper signMapper;
    @Resource
    private AppMenuMapper appMenuMapper;
    @Resource
    private SignboardMapper signboardMapper;
    @Resource
    private XrelationMapper xrelationMapper;
    @Autowired
    JwtUtils jwtUtils;
    @Resource
    private LocationMapper locationMapper;

    @Resource
    private EquipageMapper equipageMapper;

    @Resource
    private SignEquipageServiceImpl signEquipageService;

    @Resource
    private DutyrosterMapper dutyrosterMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    private final Logger log = LoggerFactory.getLogger("GPSServer");

    @Override
    public ResultBean selectByLogin(String staff_tel, String staff_password) {
        //加密
        staff_password = Md5.MD5Encode(staff_password, "utf-8");
        //根据用户密码查询
        Staff staff = staffMapper.selectByLogin(staff_tel, staff_password);
        if (staff != null) {
            //实现单点登录
            getPcIp(staff_tel);
            // 生成jwt，并放置到请求头中

            String jwt = jwtUtils.generateToken(staff_tel);

            //查询个人角色
            /*Role role = roleMapper.selectByPrimaryKey(staff.getSysRoleId());
            String subsystemuse = role.getSubsystemUsetype();
            String[] subsystemuses = subsystemuse.split(",");
            List<Subsystem> subsystems = new ArrayList<Subsystem>();
            for (int i = 0; i < subsystemuses.length; i++) {
                int subsystemid = Integer.valueOf(subsystemuses[i]);
                //查询该人使用的子系统
                Subsystem subsystem = subsystemMapper.selectByPrimaryKey(subsystemid);
                subsystems.add(subsystem);
            }
            //封装用户登录数据
            String token = tokenService.getTokenByName(staff_tel, staff_password);

            LinkedHashMap<String, Object> json = new LinkedHashMap<>();
            Verify verify = new Verify();
            BeanUtils.copyProperties(staff, verify);
            json.put("token", token);
            json.put("staff", verify);
            json.put("subsystems", subsystems);*/


            return ResultUtil.setOK("登录成功", jwt);
        }
        return ResultUtil.setOK("登录失败", null);
    }

    private void getPcIp(String staff_tel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //判断是PC还是APP
        String ua = request.getHeader("User-Agent");
        //PC端访问存起来，APP过滤掉
        if (!SysLogAspect.checkAgentIsMobile(ua)) {
            String remoteIP = SysLogAspect.getRemoteIP(request);
            System.out.println(staff_tel + "获取到的ip：" + remoteIP);
            String[] split = remoteIP.split("\\.");
            if (split.length == 4) {
                Integer integer = signboardMapper.selectCount(Wrappers.<SignBoard>lambdaQuery()
                        .eq(SignBoard::getName, staff_tel));
                SignBoard signBoard = new SignBoard();
                signBoard.setName(staff_tel);
                signBoard.setIp(remoteIP);
                signBoard.setCreateTime(new Date());
                if (integer >= 2) {
                    int delete = signboardMapper.delete(Wrappers.<SignBoard>lambdaQuery()
                            .eq(SignBoard::getName, staff_tel)
                            .orderByAsc(SignBoard::getCreateTime)
                            .last("limit 1"));
                    if (delete == 1) {

                        signboardMapper.insert(signBoard);
                    }
                } else {
                    signboardMapper.insert(signBoard);
                }

            }
        }
    }

    /**
     * 注册
     *
     * @param staff
     * @return
     */
    @Override
    public ResultBean register(Staff staff) {
        String password = Md5.MD5Encode(staff.getStaffPassword(), "utf-8");
        staff.setStaffPassword(password);
        return ResultUtil.execOp(staffMapper.insertSelective(staff), "注册");
    }

    /**
     * 校验用户是否存在
     *
     * @param name
     * @return
     */
    @Override
    public ResultBean usercheck(String name) {
        Staff staff = staffMapper.selectByName(name);
        if (staff == null) {
            ResultUtil.setOK("success", null);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "该用户已存在", staff);
    }


    /**
     * 根据id修改
     *
     * @param staff
     * @return
     */
    @Override
    public ResultBeans updaStaffInfoById(Staff staff) {
        String password = Md5.MD5Encode(staff.getStaffPassword(), "utf-8");
        staff.setStaffPassword(password);
        return ResultUtil.resultBeansexecOp(staffMapper.updateByPrimaryKeySelective(staff), "修改");
    }

    @Override
    public ResultBean updaStaffInfo(Staff staff) {
        String password = Md5.MD5Encode(staff.getStaffPassword(), "utf-8");
        staff.setStaffPassword(password);
        return ResultUtil.setOK("success", staffMapper.updateByPrimaryKeySelective(staff));
    }


    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean delStaffInfoById(Integer id) {
        //删除该人员所绑定的岗位
        xrelationMapper.deleteByStaffId(id);
        return ResultUtil.execOp(staffMapper.deleteByPrimaryKey(id), "删除");
    }


    /**
     * 手机端登录
     */
    @Override
    public ResultBean appLogin(String policeId) {

        List<Object> list = new ArrayList<>();
        //加密
        Staff staff = staffMapper.selectStaffByNums(policeId.toUpperCase());
        if (staff == null) {
            log.info("登录上传警号：" + policeId);
            return ResultUtil.setError(SystemCon.RERROR1, "error", null);
        }
        String staffPhoto = staff.getStaffPhoto();
        if (StringUtils.isNotEmpty(staffPhoto)) {
            String s = FileUpload.ReadPicture(staffPhoto);
            staff.setStaffPhoto(s);
        }
        List<AppMenu> appMenuByRole = appMenuMapper.findAppMenuByRole(staff.getAppRoleId());
        staff.setAppMenus(buildTreeMenu(appMenuByRole));
        list.add(staff);
        return ResultUtil.setOK("success", list);
    }

    public List<AppMenu> buildTreeMenu(List<AppMenu> menus) {
        List<AppMenu> finalMenus = new ArrayList<>();
        // 先各自寻找到各自的孩子
        for (AppMenu menu : menus) {
            for (AppMenu e : menus) {
                if (menu.getId().equals(e.getAppMenuPid())) {
                    menu.getChildren().add(e);
                }
            }

            // 提取出父节点
            if (menu.getAppMenuPid() == 0L) {
                finalMenus.add(menu);
            }
        }
        return finalMenus;
    }

    /**
     * 手机端APP登出
     */
    @Override
    public ResultBean appLoginOut(String IMEI, String user) {
        IMEI = null;
        return ResultUtil.execOp(registerMapper.updateRegisterByUser(IMEI, user), "登出");
    }

    /**
     * 修改唯一标识
     *
     * @param register
     * @return ResultBean
     */
    @Override
    public ResultBean updateRegiser(Register register) {
        return ResultUtil.execOp(registerMapper.updateRegisterByUser(register.getImei(), register.getUsername()), "顶掉");
    }

    /**
     * 默认人
     *
     * @param probleDetail
     * @return ResultBeans
     */
    @Override
    public ResultBeans selectdefault(String probleDetail) {
        List<Staff> selectdefault = staffMapper.selectdefault(probleDetail);
        if (selectdefault.size() > 0) {
            return ResultUtil.resultBeansSuccess(selectdefault);
        }
        return ResultUtil.resultBeansError(null);
    }

    /**
     * 修改密码
     *
     * @param staff
     * @return ResultBean
     */
    @Override
    public ResultBean modifuByPass(Staff staff) {
        //加密
        staff.setStaffPassword(Md5.MD5Encode(staff.getStaffPassword(), "utf-8"));
        int i = staffMapper.updateByPrimaryKeySelective(staff);
        if (i > 0) {
            return ResultUtil.execOp(staffMapper.updateByPrimaryKeySelective(staff), "修改密码");
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 返回各大队
     *
     * @param staffid
     * @return
     */
    @Override
    public ResultBean selectStaffBySectionName(Integer staffid) {
        Staff staff = staffMapper.selectInfoByid(staffid);

        Integer sysSectionId = staff.getSysSectionId();
        Staff staff1 = staffMapper.selectStaffBySectionName(sysSectionId);
        if (staff1 != null) {
            return ResultUtil.setOK("success", staff1);
        }

        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    @Override
    public ResultBean selectStaffInfo() {
        return ResultUtil.setOK("success", staffMapper.selectStaffInfo());
    }

    /**
     * 查询在岗人数
     *
     * @return
     */
    @Override
    public ResultBean selectStaffByzg(Integer sectionId, Integer sectionPid, String sectionName) {
        List<Staff> staff = staffMapper.selectStaffByzg(sectionId, sectionPid, sectionName);
        if (staff.size() != 0) {
            for (int i = 0; i < staff.size(); i++) {
                Gps gps = gpsMapper.gpsEnd(staff.get(i).getSysStaffId());
                staff.get(i).setGps(gps);
            }
            return ResultUtil.setOK("sucess", staff);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    @Override
    public ResultBean selectStaffByName(String Name, String staffHierarchy) {
        List<Staff> staff = staffMapper.selectStaffByName(Name, staffHierarchy);
        if (staff.size() >= 0) {
            return ResultUtil.setOK("success", staff);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 根据职位显示在线人数
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean selectStaffInfoByid(Integer id) {
        Staff staff = staffMapper.selectInfoByid(id);
        if (staff == null) {
            return ResultUtil.setError(SystemCon.RERROR1, "error", null);
        }
        if (staff.getStaffPost().equals("管理员") || staff.getStaffPost().equals("支队领导")) {
            //应到人
            List<Staff> staffglyy = staffMapper.selectStaffYdByAll(null, null, null);
            //实到
            List<Staff> staffglys = staffMapper.selectStaffByzg(null, null, null);
            for (int i = 0; i < staffglyy.size(); i++) {
                for (int q = 0; q < staffglys.size(); q++) {
                    if (staffglyy.get(i).getSysStaffId().equals(staffglys.get(q).getSysStaffId())) {
                        staffglyy.get(i).setStaffOnline("1");
                        Gps gps = gpsMapper.gpsEnd(staffglyy.get(i).getSysStaffId());
                        staffglyy.get(i).setGps(gps);
                    }
                }
            }
            return ResultUtil.setOK("success", staffglyy);
        } else if (staff.getStaffPost().equals("大队长") || staff.getStaffPost().equals("副大队长")) {
            //应到人
            List<Staff> staffglyy = staffMapper.selectStaffYdByAll(null, staff.getSysSectionId(), null);
            //实到
            List<Staff> staffglys = staffMapper.selectStaffByzg(null, null, staff.getSectionName());
            for (int i = 0; i < staffglyy.size(); i++) {
                for (int q = 0; q < staffglys.size(); q++) {
                    if (staffglyy.get(i).getSysStaffId().equals(staffglys.get(q).getSysStaffId())) {
                        staffglyy.get(i).setStaffOnline("1");
                        Gps gps = gpsMapper.gpsEnd(staffglyy.get(i).getSysStaffId());
                        staffglyy.get(i).setGps(gps);
                    }
                }
            }
            return ResultUtil.setOK("success", staffglyy);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    @Override
    public ResultBean selectStaffZx(Integer id) {
        Staff staff = staffMapper.selectInfoByid(id);
        if (staff == null) {
            return ResultUtil.setError(SystemCon.RERROR1, "error", null);
        }
        if (staff.getStaffPost() == null || staff.getStaffPost().equals("")) {
            return ResultUtil.setError(SystemCon.RERROR1, "error", null);
        }
        if (staff.getStaffPost().equals("管理员") || staff.getStaffPost().equals("支队领导")) {
            //实到
            List<Staff> staffglys = staffMapper.selectStaffByzg(null, null, null);
            for (int i = 0; i < staffglys.size(); i++) {
                staffglys.get(i).setStaffOnline("1");
                Gps gps = gpsMapper.gpsEnd(staffglys.get(i).getSysStaffId());
                staffglys.get(i).setGps(gps);
            }
            return ResultUtil.setOK("success", staffglys);
        } else if (staff.getStaffPost().equals("大队长") || staff.getStaffPost().equals("副大队长")) {
            //实到
            List<Staff> staffglys = staffMapper.selectStaffByzg(null, null, staff.getSectionName());
            for (int i = 0; i < staffglys.size(); i++) {
                staffglys.get(i).setStaffOnline("1");
                Gps gps = gpsMapper.gpsEnd(staffglys.get(i).getSysStaffId());
                staffglys.get(i).setGps(gps);
            }
            return ResultUtil.setOK("success", staffglys);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    /**
     * 查询所有的应到人实到人
     *
     * @param changeShifts
     * @return
     */
    @Override
    public ResultBean selectStaffYdByAll(String changeShifts, Integer SectionId) {
        //应到
        List<Staff> staff = staffMapper.selectStaffYdByAll(null, SectionId, null);
        //实到
        List<Staff> staff1 = staffMapper.selectpoliceZx();
        for (int i = 0; i < staff.size(); i++) {
            for (int k = 0; k < staff1.size(); k++) {
                if (staff.get(i).getSysStaffId().equals(staff1.get(k).getSysStaffId())) {
                    staff.get(i).setStaffOnline("1");
                    staff.get(i).setPatrolRecordBegintime(staff1.get(k).getPatrolRecordBegintime());
                }
            }
        }
        return ResultUtil.setOK("success", staff);
    }

    //在线
    @Override
    public ResultBean selectpoliceZx(String station) throws Exception {
        List<Staff> staff = staffMapper.selectpoliceZx();
        for (int i = 0; i < staff.size(); i++) {
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String dayTime = df.format(new Date());// new Date()为获取当前系统时间

            Date startTime = ft.parse(dayTime + " 07:30:00");
            Date endTime = ft.parse(dayTime + " 08:30:00");
            Date startTime2 = ft.parse(dayTime + " 17:30:00");
            Date endTime2 = ft.parse(dayTime + " 18:30:00");
            Date startTime3 = ft.parse(dayTime + " 08:30:00");
            Date endTime3 = ft.parse(dayTime + " 17:30:00");
            Date nowTime = new Date();
            //早高峰
            boolean effectiveDate = DataTime.hour(nowTime, startTime, endTime);
            //晚高峰
            boolean effectiveDate2 = DataTime.hour(nowTime, startTime2, endTime2);
            //固定岗 平峰期
            boolean effectiveDate3 = DataTime.hour(nowTime, startTime3, endTime3);

            //根据人查出来的岗位
            List<Xarea> xareas = xareaMapper.selectXareaZgByStaffId(staff.get(i).getSysStaffId(), station);
            for (int f = 0; f < xareas.size(); f++) {
                staff.get(i).setXarea(xareas.get(f));

            }
            Gps gps = gpsMapper.gpsEnd(staff.get(i).getSysStaffId());
            staff.get(i).setStaffOnline("1");
            staff.get(i).setGps(gps);
        }
        return ResultUtil.setOK("success", staff);
    }

    //根据id查询
    @Override
    public ResultBean selectStaffByid(Integer id) {
        Staff staff = staffMapper.selectStaffBypid(id);
        if (staff != null) {
            return ResultUtil.setOK("success", staff);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 按id查询民警应巡查路段
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean selectStaffXareaByid(Integer id) throws Exception {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String dayTime = df.format(new Date());// new Date()为获取当前系统时间

        Date startTime = ft.parse(dayTime + " 07:30:00");
        Date endTime = ft.parse(dayTime + " 09:00:00");
        Date startTime2 = ft.parse(dayTime + " 17:30:00");
        Date endTime2 = ft.parse(dayTime + " 18:30:00");
        Date startTime3 = ft.parse(dayTime + " 07:00:00");
        Date endTime3 = ft.parse(dayTime + " 20:00:00");
        Date nowTime = new Date();
        //早高峰
        boolean effectiveDate = DataTime.hour(nowTime, startTime, endTime);
        //晚高峰
        boolean effectiveDate2 = DataTime.hour(nowTime, startTime2, endTime2);
        //固定岗
        boolean effectiveDate3 = DataTime.hour(nowTime, startTime3, endTime3);
        //根据人查出来的岗位
        Staff staff = staffMapper.selectInfoByid(id);
        List<Xarea> xareas = xareaMapper.selectXareaZgByStaffId(id, null);
        List<Xarea> xareas1 = new ArrayList<>();
        //计算民警的上班时长跟巡查轨迹
        Patrolrecord patrolrecords = patrolrecordMapper.selectrecordByid(id);
        if (patrolrecords != null) {
            String patrolRecordGps = patrolrecords.getPatrolRecordGps();
            Date date = new Date();
            //上班时长
            String duration = null;
            if (patrolrecords.getPatrolRecordEndtime() == null) {
                duration = DataTime.getDatePoor(date, patrolrecords.getPatrolRecordBegintime());
            } else {
                duration = DataTime.getDatePoor(patrolrecords.getPatrolRecordEndtime(), patrolrecords.getPatrolRecordBegintime());

            }

            //巡查时长  现在时间减去签到时长
            staff.setDuration(duration);
            //巡查里程
            double juli = Double.valueOf(DistanceUtil.jq(patrolRecordGps));
            staff.setJuli(juli);
            staff.setPatrolrecord(patrolrecords);
        }


        for (int f = 0; f < xareas.size(); f++) {
            if (effectiveDate && xareas.get(f).getStation().equals("高峰岗")) {
                xareas1.add(xareas.get(f));
                staff.setXareaList(xareas1);
            } else if (effectiveDate2 && xareas.get(f).getStation().equals("高峰岗")) {
                xareas1.add(xareas.get(f));
                staff.setXareaList(xareas1);
            } else if (effectiveDate3 && xareas.get(f).getStation().equals("固定岗")) {
                staff.setXareaList(xareas);
            } else {
                staff.setXareaList(xareas);
            }

        }
        Gps gps = gpsMapper.gpsEnd(staff.getSysStaffId());
        staff.setGps(gps);
        return ResultUtil.setOK("success", staff);
    }

    @Override
    public ResultBean selectXareaByid(Integer id) throws Exception {
        List<Xarea> xareas = xareaMapper.selectXareaByid(id);
        if (xareas.size() > 0) {
            return ResultUtil.setOK("success", xareas);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 查询昨日总警力人数
     *
     * @return
     */
    @Override
    public ResultBean selecttotalforces(String battalion) {
        int selecttotalforces = staffMapper.selecttotalforces();
        return ResultUtil.setOK("success", selecttotalforces);
    }

    /**
     * 查询昨日总警力详情
     *
     * @return
     */
    @Override
    public ResultBean selecttotalforceszr(String battalion) {
        List<HashMap> selecttotalforceszr = staffMapper.selecttotalforcfb("民警", battalion);
        List<HashMap> selecttotalfjorceszr = staffMapper.selecttotalforcfb("辅警", battalion);
        for (int i = 0; i < selecttotalforceszr.size(); i++) {
            for (int k = 0; k < selecttotalfjorceszr.size(); k++) {
                if (selecttotalfjorceszr.get(k).get("sectionName").equals(selecttotalforceszr.get(i).get("sectionName"))) {
                    selecttotalforceszr.get(i).put("funum", selecttotalfjorceszr.get(k).get("count"));
                }
            }
        }
        return ResultUtil.setOK("success", selecttotalforceszr);

    }

    @Override
    public ResultBean selectzaBystation(String station, String conment, String grid, String battalion) {
        List<Staff> staff = staffMapper.selectzaBystation(station, conment, grid, battalion);
        for (int i = 0; i < staff.size(); i++) {
            Gps gps = gpsMapper.gpsEnd(staff.get(i).getSysStaffId());
            staff.get(i).setGps(gps);

        }
        if (staff.size() > 0) {
            for (int i = 0; i < staff.size(); i++) {
                String assignmentname = staff.get(i).getAssignmentname();
                if (assignmentname.contains("网格") || assignmentname.contains("铁骑") || assignmentname.contains("夜巡")) {
                    String[] split = assignmentname.split("-");
                    if (split.length >= 3) {
                        staff.get(i).setAssignmentname(split[2]);
                        staff.get(i).getXarea().setGridding(split[1]);
                        staff.get(i).setGridding(split[1]);
                    } else {
                        staff.get(i).setAssignmentname(split[1]);
                        staff.get(i).getXarea().setGridding(split[1]);
                        staff.get(i).setGridding(split[1]);
                    }
                } else {
                    String[] split = assignmentname.split("-");
                    //特殊卡口勤务没有分隔符
                    if (split.length >= 2) {
                        staff.get(i).setAssignmentname(split[1]);
                        staff.get(i).getXarea().setGridding(split[0]);
                        staff.get(i).setGridding(split[0]);
                    } else {
                        staff.get(i).setAssignmentname(split[0]);
                        staff.get(i).getXarea().setGridding(split[0]);
                        staff.get(i).setGridding(split[0]);
                    }

                }

            }
        }


        return ResultUtil.setOK("success", staff);
    }

    @Override
    public ResultBean selectStaffByqita() {
        List<Staff> staff = staffMapper.selectStaffByqita();
        for (int i = 0; i < staff.size(); i++) {
            Gps gps = gpsMapper.gpsEnd(staff.get(i).getSysStaffId());
            staff.get(i).setGps(gps);
        }
        return ResultUtil.setOK("success", staff);
    }

    /**
     * 以单位为结构显示信息列表
     *
     * @return
     */
    @Override
    public ResultBean selectAllbytype(String battalion) {

        List<HashMap> typeSumList = new ArrayList<>();
        //固定组数、应到数
        HashMap<String, Object> gdMap = new HashMap<>();
        //高峰岗组数、应到数
        HashMap<String, Object> gfMap = new HashMap<>();
        //铁骑实组数、应到数
        HashMap<String, Object> tqMap = new HashMap<>();
        //网格实组数、应到数
        HashMap<String, Object> wgMap = new HashMap<>();
        //重点组、应到实到
        HashMap<String, Object> zdMap = new HashMap<>();
        //其他组、应到实到
        HashMap<String, Object> qtMap = new HashMap<>();
        //高速
        HashMap<String, Object> gsMap = new HashMap<>();

        //实到在线人数
        List<Staff> gdorGfSDsum = staffMapper.countGdorGfSDsum("固定岗", battalion);
        List<Staff> staff = staffMapper.countGdorGfSDsumtj();

        gdMap.put("固定岗", staff);
        gdMap.put("people", gdorGfSDsum);


        typeSumList.add(gdMap);
        return ResultUtil.setOK("success", typeSumList);
    }

    @Override
    //根据岗位查询各大队在线民警
    public ResultBean selectcountBysection(Xarea xarea) {

        List<HashMap> selectcountBysection = staffMapper.selectcountBysection(xarea);
        if (selectcountBysection.size() >= 0) {
            for (int i = 0; i < selectcountBysection.size(); i++) {
                String sectionName = selectcountBysection.get(i).get("sectionName").toString();
                if (sectionName.indexOf("大队") != -1) {
                    String sectionName1 = selectcountBysection.get(i).get("sectionName").toString().substring(0, sectionName.indexOf("队") + 1);
                    selectcountBysection.get(i).put("sectionName", sectionName1);
                }
                //细分到中队
                xarea.setBattalion(String.valueOf(selectcountBysection.get(i).get("sectionName")));
                List<HashMap> hashMaps1 = staffMapper.selectcountBydetachment(xarea);
                for (int k = 0; k < hashMaps1.size(); k++) {
                    xarea.setBattalion(String.valueOf(hashMaps1.get(k).get("sectionName")));
                    List<HashMap> hashMaps = staffMapper.selectAllBysection(xarea);
                    hashMaps1.get(k).put("detachment", hashMaps);
                }

                selectcountBysection.get(i).put("detachment", hashMaps1);

            }

            return ResultUtil.setOK("success", selectcountBysection);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "success", selectcountBysection);
    }

    @Override
    //根据岗位查询各大队下各中队在线民警
    public ResultBean selectcountBydetachment(Xarea xarea) {
        List<HashMap> selectcountBydetachment = staffMapper.selectcountBydetachment(xarea);
        if (selectcountBydetachment.size() >= 0) {
            return ResultUtil.setOK("success", selectcountBydetachment);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "success", selectcountBydetachment);
    }


    /**
     * 对接市局接口  人员信息列表
     *
     * @return
     */
    @Override
    public ResultBean selectStaffByInfo() {
        return ResultUtil.setOK("success", staffMapper.selectStaffByInfo());
    }


    @Override
    public ResultBean specialOn() {
        List<HashMap> specialOnlist = staffMapper.specialOn(null);
        if (specialOnlist.size() > 0) {
            for (int i = 0; i < specialOnlist.size(); i++) {
                String sectionName = specialOnlist.get(i).get("sectionName").toString();
                if (sectionName.indexOf("大队") != -1) {
                    String sectionName1 = specialOnlist.get(i).get("sectionName").toString().substring(0, sectionName.indexOf("队") + 1);
                    specialOnlist.get(i).put("sectionName", sectionName1);
                }
                //细分到中队
                List<HashMap> hashMaps1 = staffMapper.specialOn(sectionName);
                for (int k = 0; k < hashMaps1.size(); k++) {
                    //xarea.setBattalion(String.valueOf(hashMaps1.get(k).get("sectionName")));
                    List<HashMap> hashMaps = staffMapper.specialOnment(hashMaps1.get(k).get("sectionName").toString());
                    hashMaps1.get(k).put("detachment", hashMaps);
                }

                specialOnlist.get(i).put("detachment", hashMaps1);

            }

            return ResultUtil.setOK("success", specialOnlist);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "success", null);
    }

    @Override
    public Staff selectStaffByNum(String staffNum) {
        return staffMapper.selectStaffByNum(staffNum);
    }

    @Override
    public ResultBean findStaffByid(Integer id) {
        Map<String, Object> staffByid = staffMapper.findStaffByid(id);
        if (staffByid != null) {
            //计算民警的上班时长跟巡查轨迹
            //List<Map<String, Object>> patrolrecords = patrolrecordMapper.selectrecordByDuration(id);
            List<Map<String, Object>> patrolrecords = signMapper.selectRecordSign(id);

            if (patrolrecords.size() > 0) {
                String duration;
                int time = 0;
                int mileages = 0;
                for (Map<String, Object> patrolrecord : patrolrecords) {
                    time += Integer.valueOf(patrolrecord.get("time").toString());
                    //巡查里程
                    mileages += gpsMapper.findMileages(String.valueOf(patrolrecord.get("signnum")));

                }
                if (time > 10) {
                    time = time - 10;
                }
                int hour = time / 60;
                int minute = time % 60;
                duration = hour + "小时" + minute + "分钟";
                //巡查时长  现在时间减去签到时长
                staffByid.put("duration", duration);
                //double juli = Double.valueOf(DistanceUtil.jq(patrolRecordGps));
                DecimalFormat dub = new DecimalFormat("#0.00");
                String format = dub.format((float) mileages / 1000);
                staffByid.put("juli", format);
            } else {
                //巡查时长  现在时间减去签到时长
                staffByid.put("duration", 0);
                staffByid.put("juli", 0);
            }
            Staff staff = staffMapper.selectByPrimaryKey(id);
            //Equipage locationEnd = equipageMapper.findEquipageEnd(staff.getStaffNum());
            Location locationEnd = locationMapper.findLocationEnd(staff.getSysStaffId());
            if (locationEnd != null) {
                staffByid.put("gpsX", locationEnd.getLongitude());
                staffByid.put("gpsY", locationEnd.getLatitude());
            }
            List<Map<String, Objects>> equipageById = signEquipageService.getEquipageBy(staff.getStaffTel());
            staffByid.put("equipages", equipageById);
            return ResultUtil.setOK("success", staffByid);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    @Override
    public ResultBean findStaffByWarningSignal(Integer sectionId, String warningSignal) {
        List<Map> staffByWarningSignal = staffMapper.findStaffByWarningSignal(sectionId, warningSignal);
        return ResultUtil.setOK("success", staffByWarningSignal);
    }

    @Override
    public Staff selectByPrimaryKey(Integer sysStaffId) {
        return this.staffMapper.selectByPrimaryKey(sysStaffId);
    }

    @Override
    public Map selectStaffInfoById(Integer sysStaffId) {
        return this.staffMapper.selectStaffInfoById(sysStaffId);
    }


    @Override
    public List<Staff> selectStaffBySectionID(Integer sys_section_id) {
        return this.staffMapper.selectStaffBySectionID(sys_section_id);
    }

    /**
     * 新增人员
     *
     * @param staff 封装人员的参数
     * @return ResultBean
     */
    @Override
    @Transactional
    public ResultBean addStaff(Staff staff) {
        if (null != staff.getStaffPassword()) {
            staff.setStaffPassword(Md5.MD5Encode(staff.getStaffPassword(), "utf-8"));
        }
        if (Objects.isNull(staff.getStafftype())) {
            staff.setStafftype("管理员");
        }
        Staff staff1 = staffMapper.selectOne(Wrappers.<Staff>lambdaQuery()
                .eq(Staff::getStaffTel, staff.getStaffTel()));
        if (Objects.nonNull(staff1)) {
            return ResultUtil.setError(500, "存在相同的账号", null);
        }
        int insert = staffMapper.insert(staff);
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(Long.valueOf(staff.getSysStaffId()));
        sysUserRole.setRoleId(staff.getRoleId());

        sysUserRoleMapper.insert(sysUserRole);
        if (insert > 0) {
            return ResultUtil.setOK("新增成功", null);
        } else {
            return ResultUtil.setError(500, "新增失败", null);
        }
    }

    /**
     * 更新人员
     *
     * @param staff 封装人员的参数
     * @return ResultBean
     */
    @Override
    public ResultBean updateStaff(Staff staff) {
        if (null != staff.getStaffPassword()) {
            staff.setStaffPassword(Md5.MD5Encode(staff.getStaffPassword(), "utf-8"));
        }
        //如果电台号不为空，同步更新一下电台号
        if (StringUtils.isNotEmpty(staff.getDigitalRadio())) {
            Dutyroster dutyroster = new Dutyroster();
            dutyroster.setCreatTime(new Date());
            dutyroster.setGpsid(staff.getDigitalRadio());
            dutyrosterMapper.insertIgnoreNull(dutyroster);
        }

        int update = staffMapper.updateByPrimaryKeySelective(staff);
        if (1 == update) {
            return ResultUtil.setOK("修改成功", null);
        } else {
            return ResultUtil.setError(500, "修改失败", null);
        }
    }

    /**
     * 批量插入人员
     *
     * @param staff 封装人员的参数
     * @return ResultBean
     */
    @Override
    public ResultBean addAllStaff(List<Staff> staff) {
        int i = staffMapper.insertAll(staff);
        if (0 < i) {
            return ResultUtil.setOK("插入成功", null);
        } else {
            return ResultUtil.setError(500, "插入失败", null);
        }
    }


    /**
     * 根据岗位查询在线人员详情
     *
     * @param station 岗位
     * @return ResultBean
     */
    @Override
    public ResultBean OnlineDetails(String station, String battalion) {
        //分割大队
        if (battalion != null) {
            battalion = battalion.substring(0, battalion.indexOf("队") + 1);
            if ("交警支队".equals(battalion)) {
                battalion = null;
            }

        }
        //在线大队
        List<HashMap> mapList = signMapper.OnlineBattalion(station, battalion);
        for (HashMap hashMap : mapList) {
            String sectionname = hashMap.get("sectionName").toString();
            String sectionName = sectionname.substring(0, sectionname.indexOf("队") + 1);
            hashMap.put("sectionName", sectionName);
            //在线中队
            List<HashMap> hashMaps = signMapper.OnlineByBattalion(station, sectionName);
            for (HashMap map : hashMaps) {
                String sectionname1 = map.get("sectionName").toString();
                map.put("sectionName", sectionname1);
                //在线人员详情
                List<Map> signs = signMapper.OnlineStaffId(station, sectionname1);
                map.put("detachment", signs);
                map.put("count", signs.size());
            }
            hashMap.put("detachment", hashMaps);
        }
        return ResultUtil.setOK("success", mapList);
    }


    @Override
    public List<Map> findStaffInfoByAll(String staffName, String warningsignal, Integer sectionid, String staffType) {
        return staffMapper.findStaffInfoByAll(staffName, warningsignal, sectionid, staffType);
    }

    @Override
    public PageInfo<Map> findStaffInfoByPage(String staffName, String warningsignal, Integer sectionid, String staffType, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map> staffInfoByAll = staffMapper.findStaffInfoByAll(staffName, warningsignal, sectionid, staffType);
        PageInfo<Map> pageInfo = new PageInfo<>(staffInfoByAll);
        return pageInfo;
    }


    /**
     * 根据大队、中队、民警辅警、在线/不在线、岗位
     *
     * @param matching 入参
     * @return ResultBean
     */
    @Override
    public ResultBean selectStaffMatching(Matching matching) {
        List<Map> mapList = staffMapper.selectStaffMatching(matching);
        return ResultUtil.setOK("success", mapList);
    }

    @Override
    public ResultBean selectStaffOnLine(Matching matching, Integer current, Integer size) {
        if (StringUtils.isNotEmpty(matching.getIsOnline())) {
            switch (matching.getIsOnline()) {
                case "1":
                    PageHelper.startPage(current, size);
                    //查询在线数据警员
                    List<Map<String, Object>> mapList = staffMapper.selectStaffOnLine(matching);
                    PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
                    return ResultUtil.setOK("success", pageInfo);
                case "2":
                    PageHelper.startPage(current, size);
                    //查询不在线警员
                    List<Map<String, Object>> mapList1 = staffMapper.selectStaffOffLine(matching);
                    PageInfo<Map<String, Object>> pageInfo1 = new PageInfo<>(mapList1);
                    return ResultUtil.setOK("success", pageInfo1);
            }
        }

        //查询在线数据警员
        List<Map<String, Object>> mapList = staffMapper.selectStaffOnLine(matching);
        //查询不在线警员
        List<Map<String, Object>> mapList1 = staffMapper.selectStaffOffLine(matching);
        //合并
        List<Map<String, Object>> merge = DistanceUtil.merge(mapList, mapList1);

        PageUtils<Map<String, Object>> pu = new PageUtils<>(current, size, merge.size());
        //查当前页数据
        List<Map<String, Object>> paging = subList(merge, current, size);
        if (paging != null) {
            pu.setList(paging);
        } else {
            pu.setList(new ArrayList<>());
        }

        return ResultUtil.setOK("success", pu);


    }

    @Override
    public String exportStaffOnLine(HttpServletResponse response, Matching matching) throws IOException {
        List<Map<String, Object>> online = new ArrayList<>();
        if (StringUtils.isNotEmpty(matching.getIsOnline())) {
            switch (matching.getIsOnline()) {
                case "1":
                    //查询在线数据警员
                    online = staffMapper.selectStaffOnLine(matching);
                    break;
                case "2":
                    //查询不在线警员
                    online = staffMapper.selectStaffOffLine(matching);
                    break;
            }
        } else {
            //查询在线数据警员
            List<Map<String, Object>> mapList = staffMapper.selectStaffOnLine(matching);
            //查询不在线警员
            List<Map<String, Object>> mapList1 = staffMapper.selectStaffOffLine(matching);
            //合并
            online = DistanceUtil.merge(mapList, mapList1);
        }

        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 设置只导出有别名的字段
        writer.setOnlyAlias(true);
        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
        for (Map<String, Object> map : online) {
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("警号", map.get("staff_num"));
            row1.put("姓名", map.get("staff_name"));
            row1.put("单位", map.get("sectionname"));
            row1.put("警力类型", map.get("stafftype"));
            if ("1".equals(map.get("state").toString())) {
                row1.put("是否在线", "是");
            } else {
                row1.put("是否在线", "否");
            }

            rows.add(row1);
        }
        String fileName = System.currentTimeMillis() + ".xlsx";
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(4, "在线统计统计导出");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);

        writer.setRowHeight(-1, 20);
        writer.setColumnWidth(-1, 15);


        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        ServletOutputStream out = response.getOutputStream();
        // 关闭writer，释放内存
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);

        return fileName;
    }

    //subList手动分页，page为第几页，rows为每页个数
    public static List<Map<String, Object>> subList(List<Map<String, Object>> list, int page, int rows) {
        List<Map<String, Object>> listSort = new ArrayList<>();
        int size = list.size();
        int pageStart = page == 1 ? 0 : (page - 1) * rows;//截取的开始位置
        int pageEnd = size < page * rows ? size : page * rows;//截取的结束位置
        if (size > pageStart) {
            listSort = list.subList(pageStart, pageEnd);
        }
        //总页数
        //int totalPage = list.size() / rows;
        return listSort;
    }


    @Override
    public ResultBean selectCommandCenter() {
        List<Map> mapList = staffMapper.selectCommandCenter();

        return ResultUtil.setOK("success", mapList);
    }

    @Override
    public Staff getByUsername(String username) {

        return staffMapper.selectOne(Wrappers.<Staff>lambdaQuery().eq(Staff::getStaffTel, username));
    }

    @Override
    public ResultBean roleUser(RoleUserVo role) {
        PageHelper.startPage(role.getPageNum(), role.getPageSize());
        List<Staff> staff = staffMapper.roleUser(role.getRoleId());
        PageInfo<Staff> page = new PageInfo<>(staff);
        if (Objects.isNull(role.getRoleId())) {
            List<Staff> staffs = staffMapper.selectList(Wrappers.<Staff>lambdaQuery().eq(Staff::getStafftype, "管理员"));
            return ResultUtil.setOK("查询成功", staffs);
        }
        return ResultUtil.setOK("查询成功", page);
    }


}
